package program;

import java.util.List;

import kernel.IOManager;
import kernel.exception.OSException;
import kernel.process.AbstractProcess;
import kernel.process.AbstractProcessHeader;

/**
 * Exit process.
 * For more see man() method.
 * @author Jaromir Lepic
 *
 */
public class Exit extends AbstractProcess {
	
	public static final String ALL = "-a";
	public static final String ALL2 = "--all";
	private boolean doAll = false;
	
	public Exit(AbstractProcessHeader header, long pid) {
		super(header, pid);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String continueJob() throws OSException {
		shouldEnd = true;
		return null;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected String finalizeJob() throws OSException {
		return null;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected String doJob(String input) throws OSException {
		for (String param: params){
			if (param.toLowerCase().equals(ALL) || param.toLowerCase().equals(ALL2)){
				doAll = true;
			}
		}
		
		if (doAll){
			List <Shell> list = IOManager.getInstance().getShells(shellID);
			while (list != null && !list.isEmpty()){
				list.get(0).killProcess();
			}
		} else {
			IOManager.getInstance().getActiveShell(shellID).killProcess();
			return "Shell terminated";
		}
		return null;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean needParams() {
		return false;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected void kill() throws OSException {
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String man(String command) {
		String man = "";
		
		man += "    terminates current active shell\n";
		man += "\n";
		man += "Command syntax:\n";
		man += "    "+command+" [OPTION]\n";
		man += "\n";
		man += "Description:\n";
		man += "    -a/--all - terminates all shells in current window\n";
		man += "\n";
		man += "Examples:\n";
		man += "    "+command+" -a\n";
		
		return man;
	
	}

}
